package com.zbkj.crmeb.merchant.api.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.CommonPage;
import com.constants.Constants;
import com.crmeb.core.common.CommonResult;
import com.common.PageParamRequest;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageInfo;
import com.taobao.pac.sdk.cp.dataobject.request.MODUAN_ORDER_CREATE.request;
import com.utils.CrmebUtil;
import com.zbkj.crmeb.chant.response.ChannelDiscountPackageResponse;
import com.zbkj.crmeb.chant.response.PickingProductResponse;
import com.zbkj.crmeb.chant.service.ChannelDiscountPackageService;
import com.zbkj.crmeb.chant.service.ChannelPickingService;
import com.zbkj.crmeb.front.request.IndexStoreProductSearchRequest;
import com.zbkj.crmeb.front.request.ProductRequest;
import com.zbkj.crmeb.front.response.ProductDetailResponse;
import com.zbkj.crmeb.front.response.ProductResponse;
import com.zbkj.crmeb.front.response.StoreProductReplayCountResponse;
import com.zbkj.crmeb.merchant.admin.service.MerStoreProductService;
import com.zbkj.crmeb.merchant.admin.service.StoreProductStockService;
import com.zbkj.crmeb.merchant.api.response.AppletPickingProductResponse;
import com.zbkj.crmeb.merchant.api.response.FrontPickingResponse;
import com.zbkj.crmeb.merchant.api.service.MerProductService;
import com.zbkj.crmeb.store.response.*;
import com.zbkj.crmeb.store.service.ChannelGroupBookingService;
import com.zbkj.crmeb.supplier.model.SupplierOpenShop;
import com.zbkj.crmeb.supplier.service.SupplierOpenShopService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 商户-商品
 */
@RestController("MerProductController")
@RequestMapping("api/front/mer")
@Api(tags = "商品")
@Slf4j
public class FontProductController extends ApiBaseController {
    @Autowired
    private MerProductService productService;
    @Autowired
    private MerStoreProductService storeProductService;
    @Autowired
    private SupplierOpenShopService supplierOpenShopService;
    @Autowired
    private StoreProductStockService storeProductStockService;
    @Autowired
    private ChannelPickingService channelPickingService;
    @Autowired
    private ChannelGroupBookingService channelGroupBookingService;
    @Autowired
    private ChannelDiscountPackageService channelDiscountPackageService;

    /**
     * 为你推荐
     * @author Mr.Zhang
     * @since 2020-06-02
     */
    @ApiOperation(value = "为你推荐")
    @RequestMapping(value = "/product/hot", method = RequestMethod.GET)
    public CommonResult<CommonPage<ProductResponse>> getMenuUser(@Validated PageParamRequest pageParamRequest, HttpServletRequest servletRequest){
        IndexStoreProductSearchRequest request = new IndexStoreProductSearchRequest();
        request.setIsHot(true);
        request.setMerId(getMerId(servletRequest));
        return CommonResult.success(productService.getIndexProduct(request, pageParamRequest, null));
    }

    /**
     * 商品列表
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @ApiOperation(value = "商品列表")
    @RequestMapping(value = "/products", method = RequestMethod.GET)
    public CommonResult<CommonPage<ProductResponse>> getList( @Validated ProductRequest request, @Validated PageParamRequest pageParamRequest, HttpServletRequest servletRequest) throws Exception{
        request.setMerId(getMerId(servletRequest));
        return CommonResult.success(productService.getList(request, pageParamRequest));
    }

    /**
     * 商品列表 - 图搜
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @ApiOperation(value = "商品列表 - 图搜")
    @RequestMapping(value = "/products/tusou", method = RequestMethod.POST)
    public CommonResult<CommonPage<ProductResponse>> getListByTuSou(@ApiParam(name="searchFlag",value="图搜方式", required = true) Boolean searchFlag, @ApiParam(name="targetImage",value="上传图片") MultipartFile targetImage, @Validated ProductRequest request, @Validated PageParamRequest pageParamRequest, HttpServletRequest servletRequest) throws Exception{
        log.info("商品列表 - 图搜入口:{},,", JSONObject.toJSONString(request));
        String groupId = null;
        Integer  leaderId = 0;
        String jsonStr = servletRequest.getParameter(Constants.JSON_STR);
        log.info("商品列表 - 图搜 jsonStr:{}", jsonStr);
        if(StringUtils.isNotEmpty(jsonStr)) {
//            try {
//                leaderId = Integer.valueOf(jsonStr);
//            }catch (Exception e){
//                log.error("商品列表 - 图搜 数据转换错误 jsonStr:{}", jsonStr);
//                leaderId = 0;
//            }
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            if(null != jsonObject && null != jsonObject.get("groupId")) {
                groupId = jsonObject.get("groupId").toString();
            }
            if(null != jsonObject && null != jsonObject.get("leaderId")) {
                try {
                    leaderId = Integer.valueOf(jsonObject.get("leaderId").toString());
                }catch (Exception e){
                    log.error("商品列表 - 图搜 数据转换错误 jsonStr:{}", jsonStr);
                    leaderId = 0;
                }
//                if(StringUtils.isNotEmpty(leaderId) && !"0".equals(leaderId)){
//                    groupId = storeProductStockService.getGroupIdByProductIdAndLeaderIdV2(leaderId, id,  getMerId(servletRequest));
//                }
            }
            log.info("商品列表 - 图搜:{},{},", leaderId, groupId);
        }else{
            log.info("商品列表 - 图搜2:{},{},", jsonStr,leaderId, groupId);
        }
        request.setMerId(getMerId(servletRequest));
        CommonPage<ProductResponse> tuSouPage = productService.getListByTuSou(targetImage, request, pageParamRequest, leaderId);
        return CommonResult.success(tuSouPage);
    }

    /**
     * 商品详情
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @ApiOperation(value = "多供应商商品详情")
    @RequestMapping(value = "/product/detail/{id}", method = RequestMethod.GET)
    public CommonResult<StoreProductDetailNormResponse> getDetail(@PathVariable Integer id, Integer activityId, HttpServletRequest servletRequest){
        log.info("多供应商商品详情入口:{},{},{},", id,activityId);
        String shopId = null;
        String groupId = null;
        String  leaderId = null;
        String jsonStr = servletRequest.getParameter(Constants.JSON_STR);
        log.info("多供应商商品详情 jsonStr:{}", jsonStr);
        if(StringUtils.isNotEmpty(jsonStr)) {
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            if(null != jsonObject && null != jsonObject.get("groupId")) {
                groupId = jsonObject.get("groupId").toString();
            }
            if(null != jsonObject && null != jsonObject.get("shopId")) {
                shopId = jsonObject.get("shopId").toString();
            }
            if(null != jsonObject && null != jsonObject.get("leaderId")) {
                leaderId = jsonObject.get("leaderId").toString();
                if(StringUtils.isNotEmpty(leaderId) && !"0".equals(leaderId)){
                    groupId = storeProductStockService.getGroupIdByProductIdAndLeaderIdV2(leaderId, id,  getMerId(servletRequest));
                }
            }
            log.info("多供应商商品详情:{},{},{}, {}", id,activityId, groupId);
        }else{
            log.info("多供应商商品详情2:{},{},{}, {}", id,activityId, groupId);
        }
        Integer merId = 0;
        if(StringUtils.isNotEmpty(shopId) && !"0".equals(shopId)){
            try {
                SupplierOpenShop shop = supplierOpenShopService.getById(shopId);
                merId = shop.getShopMerId();
            }catch (Exception e){
                log.error("多供应商商品详情 渠道商户不存在，请检查入参 jsonStr:{}", jsonStr);
                throw new CrmebException("渠道商户不存在，请检查入参！");
            }

        }else {
            merId = getMerId(servletRequest);
        }
        if(merId == null || merId == 0){
            throw new CrmebException("渠道商户不存在，请检查入参！");
        }
        return CommonResult.success(productService.getDetailNorm(id, merId,activityId,groupId));
    }
    
    /**
     * 商品详情
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @ApiOperation(value = "单供应商商品详情")
    @RequestMapping(value = "/product/noauth/detail/{id}", method = RequestMethod.GET)
    public CommonResult<ProductDetailResponse> getNoAuthDetail(@PathVariable Integer id,Integer activityId, HttpServletRequest servletRequest){
        log.info("单供应商商品详情入口:{},{},{},", id,activityId);
        Map<String, String[]> parameterMap = servletRequest.getParameterMap();
        String jsonStr2 = JSONObject.toJSONString(parameterMap);
        log.info("接收到 request jsonStr2:{}",jsonStr2);
        JSONObject obj = JSONObject.parseObject(jsonStr2);
        log.info("接收到 request obj :{}",obj.toJSONString());
        String shopId = null;
        String groupId = null;
        String  leaderId = null;
        String jsonStr = servletRequest.getParameter(Constants.JSON_STR);
        log.info("单供应商商品详情 jsonStr:{}", jsonStr);
        if(StringUtils.isNotEmpty(jsonStr)) {
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            if(null != jsonObject && null != jsonObject.get("groupId")) {
                groupId = jsonObject.get("groupId").toString();
            }
            if(null != jsonObject && null != jsonObject.get("shopId")) {
                shopId = jsonObject.get("shopId").toString();
            }
            if(null != jsonObject && null != jsonObject.get("leaderId")) {
                leaderId = jsonObject.get("leaderId").toString();
                if(StringUtils.isNotEmpty(leaderId) && !"0".equals(leaderId)){
                    groupId = storeProductStockService.getGroupIdByProductIdAndLeaderIdV2(leaderId, id,  getMerId(servletRequest));
                    log.info("单供应商商品详情 groupId:{}", groupId);
                }
            }
            log.info("单供应商商品详情:{},{},{}, {}, {}", id, activityId, jsonStr, jsonObject, groupId);
        }else {
            log.info("单供应商商品详情2:{},{},{}, {}", id, activityId, jsonStr, groupId);
        }
        Integer merId = 0;
        if(StringUtils.isNotEmpty(shopId) && !"0".equals(shopId)){
            try {
                SupplierOpenShop shop = supplierOpenShopService.getById(shopId);
                merId = shop.getShopMerId();
            }catch (Exception e){
                log.error("单供应商商品详情 渠道商户不存在，请检查入参 jsonStr:{}", jsonStr);
                throw new CrmebException("渠道商户不存在，请检查入参！");
            }

        }else {
            merId = getMerId(servletRequest);
        }
        if(merId == null || merId == 0){
            throw new CrmebException("渠道商户不存在，请检查入参！");
        }
        return CommonResult.success(productService.getDetail(id, merId,activityId, groupId));
    }

    /**
     * 商品评论列表
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @ApiOperation(value = "商品评论列表")
    @RequestMapping(value = "/reply/list/{id}", method = RequestMethod.GET)
    @ApiImplicitParam(name = "type", value = "评价等级|0=全部,1=好评,2=中评,3=差评", allowableValues = "range[0,1,2,3]")
    public CommonResult<CommonPage<StoreProductReplyResponse>> getReplyList(
            @PathVariable Integer id,
            @RequestParam(value = "type") Integer type,
            @Validated PageParamRequest pageParamRequest){
        return CommonResult.success(CommonPage.restPage(productService.getReplyList(id, type, pageParamRequest)));
    }

    /**
     * 商品评论数量
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @ApiOperation(value = "商品评论数量")
    @RequestMapping(value = "/reply/config/{id}", method = RequestMethod.GET)
    public CommonResult<StoreProductReplayCountResponse> getReplyCount(@PathVariable Integer id){
        return CommonResult.success(productService.getReplyCount(id));
    }

    /**
     * 待支付与待发货的库存数量
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @ApiOperation(value = "库存数量")
    @RequestMapping(value = "/stock/count", method = RequestMethod.GET)
    public CommonResult<Integer> getStockCount(Integer productId,String sourceSkuId,String size){
        return CommonResult.success(productService.getStockCount(productId,sourceSkuId,size));
    }
    /**
     * 分页显示商品表(供应商自建商品)
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "通过ids查询商品列表")
    @RequestMapping(value = "/product/listByIds2", method = RequestMethod.POST)
    public CommonResult<List<StoreProductResponse>> getListByIds2(@RequestBody List<Integer> ids, HttpServletRequest servletRequest) {
//        List<StoreProductResponse> list = storeProductService.getMerchnatList(ids,getMerId(servletRequest),true);
        List<StoreProductResponse> list = storeProductService.getFrontMerchnatList2(ids,getMerId(servletRequest));
        if (list==null){
            return CommonResult.success(new ArrayList<>());
        }
        return CommonResult.success(list);
    }

    /**
     * 分页显示商品表(供应商自建商品)
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "通过ids查询商品列表")
    @RequestMapping(value = "/product/listByIds", method = RequestMethod.POST)
    public CommonResult<List<StoreProductResponse>> getListByIds(@RequestBody List<Integer> ids, HttpServletRequest servletRequest) {
//        List<StoreProductResponse> list = storeProductService.getMerchnatList(ids,getMerId(servletRequest),true);
        log.info("通过ids查询商品列表入口:{},,", JSONObject.toJSONString(ids));
        String groupId = null;
        Integer  leaderId = 0;
        String jsonStr = servletRequest.getParameter(Constants.JSON_STR);
        log.info("通过ids查询商品列表 jsonStr:{}", jsonStr);
        if(StringUtils.isNotEmpty(jsonStr)) {
//            try {
//                leaderId = Integer.valueOf(jsonStr);
//            }catch (Exception e){
//                log.error("商品列表 - 图搜 数据转换错误 jsonStr:{}", jsonStr);
//                leaderId = 0;
//            }
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            if(null != jsonObject && null != jsonObject.get("groupId")) {
                groupId = jsonObject.get("groupId").toString();
            }
            if(null != jsonObject && null != jsonObject.get("leaderId")) {
                try {
                    leaderId = Integer.valueOf(jsonObject.get("leaderId").toString());
                }catch (Exception e){
                    log.error("通过ids查询商品列表 数据转换错误 jsonStr:{}", jsonStr);
                    leaderId = 0;
                }
            }
            log.info("通过ids查询商品列表:{},{},", leaderId, groupId);
        }else{
            log.info("通过ids查询商品列表2:{},{},", jsonStr,leaderId, groupId);
        }
        List<StoreProductResponse> list = storeProductService.getFrontMerchnatList(ids,getMerId(servletRequest), leaderId);
        if (list==null){
            return CommonResult.success(new ArrayList<>());
        }
        return CommonResult.success(list);
    }

    @ApiOperation(value = "批采单列表")
    @GetMapping(value = "/picking/list")
    public CommonResult<CommonPage<FrontPickingResponse>> getPickingList(@Validated PageParamRequest pageParamRequest, HttpServletRequest servletRequest){
        PageInfo<FrontPickingResponse> pageInfo = channelPickingService.getPickingList(getMerId(servletRequest), pageParamRequest);
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    @ApiOperation(value = "货单列表")
    @GetMapping(value = "/picking/products/{pickingId}")
    public CommonResult<CommonPage<AppletPickingProductResponse>> getPickingProducts(@PathVariable("pickingId") Integer pickingId, @Validated PageParamRequest pageParamRequest, HttpServletRequest servletRequest){
        PageInfo<AppletPickingProductResponse> pageInfo = channelPickingService.getPickingProducts(pickingId,getMerId(servletRequest), pageParamRequest);
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    @ApiOperation(value = "批采购物车")
    @GetMapping(value = "/picking/cart/{pickingId}")
    public CommonResult<List<StoreCartResponse>> getPickingCart(@PathVariable("pickingId") Integer pickingId, HttpServletRequest servletRequest){
        List<StoreCartResponse> list = channelPickingService.getPickingCart(pickingId,getMerId(servletRequest));
        return CommonResult.success(list);
    }

    /**
     * 商品列表
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @ApiOperation(value = "扫一扫检索商品")
    @RequestMapping(value = "/products/barcode", method = RequestMethod.GET)
    public CommonResult<CommonPage<ProductResponse>>getProductByBarcode( @Validated ProductRequest request, @Validated PageParamRequest pageParamRequest,HttpServletRequest servletRequest) throws Exception{
        request.setMerId(getMerId(servletRequest));
        return CommonResult.success(productService.getListByBarcode(request,pageParamRequest));
    }

    @ApiOperation(value = "优惠套餐详情")
    @RequestMapping(value = "/discount/{id}", method = RequestMethod.GET)
    public CommonResult<ChannelDiscountPackageResponse> getPackageDiscountInfo(@PathVariable Integer id) {
        return CommonResult.success(channelDiscountPackageService.getInfo(id));
    }

    @ApiOperation(value = "搜索联想")
    @GetMapping("/search")
    public CommonResult<List<String>> getProductNameByKeywords(String keywords, HttpServletRequest request) {
        return CommonResult.success(storeProductService.getProductNameByKeywords(keywords, getMerId(request)));
    }

}



